import React, { useEffect, useState } from 'react'
import { Layout, Menu } from 'antd';
import { useNavigate ,NavLink,useLocation} from 'react-router-dom';
import axios from 'axios'
import {connect} from 'react-redux'
import {
  // UploadOutlined,
  UserOutlined,
  // VideoCameraOutlined,
  // AppstoreOutlined
} from '@ant-design/icons';
import './index.css'
const { Sider, } = Layout;
 function SideMenu(props) {
  useEffect(()=>{
    axios.get('http://localhost:8000/rights?_embed=children').then(res=>{
      // console.log(res.data);
      // console.log("pathname:", pathname)
      setlist(res.data)
    })
   
  },[])
  const iconlist={
    '/home':<UserOutlined></UserOutlined>,
    '/user-manage':<UserOutlined></UserOutlined>,
    '/user-manage/list':<UserOutlined></UserOutlined>,
    '/right-manage':<UserOutlined></UserOutlined>,
    '/right-manage/role/list':<UserOutlined></UserOutlined>,
    '/right-manage/right/list':<UserOutlined></UserOutlined>,
  }
  const navigate = useNavigate()
  const location = useLocation()
  const [list,setlist] = useState([])
  const [collapsed, setCollapsed] = useState(false);


  const {role:{rights}} =JSON.parse(localStorage.getItem('token'))
  const obj = (key, icon, label, children) => {
    return {
      key,
      icon,
      label,
      children,
    }
  }
  const dfs1 = (list) => {
    const arr = []
    list.map((item) => {
      if (item.children && item.children.length !== 0) {
        return(
          rights.includes(item.key)&&
         arr.push(
          obj(item.key, iconlist[item.key], item.label, dfs1(item.children))
        ) )
      } else {
        return (
          item.pagepermisson && 
          rights.includes(item.key)&&
          arr.push(obj(item.key, iconlist[item.key], item.label)) 
        )
      }
    })
    return arr
  }
  const urlParams = new URL(window.location.href);
  const pathname = urlParams?.pathname;


  const click=(e)=>{
    if(pathname!==e.key)
    {
    navigate(e.key)
  }
  }

  const selectKeys = [location.pathname]
  const openKeys =['/'+location.pathname.split('/')[1]]
  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsed}>
    <div style={{display:'flex',height:'100%','flexDirection':'column'}}>
    <div className="logo">全球新闻发布管理系统</div>
    <div style={{flex:'1',overflow:'auto'}}>
    <Menu
        onClick={click}
        theme="dark"
        mode="inline"
        selectedKeys={selectKeys}
        items={dfs1(list)}
        defaultOpenKeys={openKeys}
      />
    </div>
    </div>
    </Sider>
  )
}

const mapStateToProps=({CollApsedReducer:{isCollapsed}})=>({
  isCollapsed
})

export default connect(mapStateToProps,)(SideMenu)
